import Nerv from "nervjs";
import Taro, { showToast as _showToast, makePhoneCall as _makePhoneCall } from "@tarojs/taro-h5";
import { View, Image } from '@tarojs/components';
import { AtButton, AtTimeline, AtDivider, AtCurtain, AtGrid, AtInput, AtNavBar, AtAccordion, AtActivityIndicator } from 'taro-ui';
import Actions from '../../utils/actions';
import Api from '../../utils/api';
import Utils from '../../utils/utils';
import Global from '../../utils/global';
import './detail.scss';
export default class Detail extends Taro.Component {
  constructor() {
    super(...arguments);

    this.state = {
      data: null,
      loading: true,
      open_state: [true, false, false, false, false, true],
      preview_item: null,
      preview_state: false
    };
  }
  async componentWillMount() {
    const wo = Global.get('wo');
    if (!wo) {
      _showToast({
        title: '载入数据失败，返回前步操作',
        icon: 'loading',
        duration: 2000,
        success: () => {
          Taro.navigateBack();
        }
      });
    } else {
      const res = await Api.request(Actions.FLOW, { wo_id: wo.id });
      const data = res.data;
      this.setState({
        data: {
          wo: wo,
          flow: data.list
        },
        loading: false
      });
    }
  }
  handleCallMobile(mobile) {
    _makePhoneCall({
      phoneNumber: mobile
    });
  }
  handleOpenStateChanged(index) {
    const { open_state } = this.state;
    let state = Object.assign([], open_state);
    state[index] = !state[index];
    this.setState({
      open_state: state
    });
  }
  handleImageClick(item, index) {
    this.setState({
      preview_item: item,
      preview_state: true
    });
  }
  handlePreviewClose() {
    this.setState({
      preview_item: null,
      preview_state: false
    });
    Utils.debug('handlePreviewClose');
  }
  renderUserInfo(user, title, state_index) {
    const { open_state } = this.state;
    return <AtAccordion open={open_state[state_index]} onClick={this.handleOpenStateChanged.bind(this, state_index)} title={title}>
      <AtInput name="username" title="用户名" type="text" placeholder="用户名" value={user.username} editable={false} />
      <AtInput name="full_name" title="姓名" type="text" placeholder="姓名" value={user.full_name} editable={false} />
      <AtInput name="dept" title="部门" type="text" placeholder="部门" value={user.dept} editable={false} />
      <AtInput name="mobile" title="电话" type="text" placeholder="电话" value={user.mobile} editable={false} />
      <AtInput name="address" title="地址" type="text" placeholder="地址" value={user.address} editable={false} />
      <AtButton type="primary" onClick={this.handleCallMobile.bind(this, user.mobile)}>
        电话呼叫
      </AtButton>
    </AtAccordion>;
  }
  renderResourceInfo(res, title, state_index) {
    const { open_state } = this.state;
    return <AtAccordion open={open_state[state_index]} onClick={this.handleOpenStateChanged.bind(this, state_index)} title={title}>
      <AtInput name="res_cate" title="资源分类" type="text" placeholder="资源分类" value={res.cate.title + '(' + res.cate.unit + ')'} editable={false} />
      <AtInput name="model" title="型号" type="text" placeholder="型号" value={res.model} editable={false} />
      <AtInput name="spec" title="规格" type="text" placeholder="规格" value={res.spec} editable={false} />
      <AtInput name="brand" title="品牌" type="text" placeholder="品牌" value={res.brand} editable={false} />
      <AtInput name="sn" title="序列号" type="text" placeholder="序列号" value={res.sn} editable={false} />
      <AtInput name="address" title="位置" type="text" placeholder="位置" value={res.address} editable={false} />
    </AtAccordion>;
  }
  renderImagePreviewer() {
    const { preview_state, preview_item } = this.state;
    return <AtCurtain isOpened={preview_state} onClose={this.handlePreviewClose.bind(this)}>
      {preview_item && <Image style="width:100%;" src={preview_item.image} />}
    </AtCurtain>;
  }
  renderImages() {
    const { data } = this.state;
    let images = [];
    data.wo.images.forEach(image => {
      images.push({
        image: image.url,
        value: image.title
      });
    });
    return <AtGrid mode="rect" data={images} onClick={this.handleImageClick.bind(this)} />;
  }
  renderCaption() {
    return <View style="">
      <AtNavBar color="#000" title="工单详情" leftText="返回" leftIconType="chevron-left" onClickLeftIcon={Taro.navigateBack} />
    </View>;
  }
  renderWo(title, state_index) {
    const { data, open_state } = this.state;
    return <AtAccordion open={open_state[state_index]} onClick={this.handleOpenStateChanged.bind(this, state_index)} title={title}>
      <View className="at-article" style="padding:10px;">
        <View className="at-article__h3">工单类型：{data.wo.cate.title}</View>
        <AtDivider height={30} lineColor="#d6e4ef" />
        <View className="at-article__h3">工单编号：{data.wo.code}</View>
        <AtDivider height={30} lineColor="#d6e4ef" />
        <View className="at-article__h3">问题描述</View>
        <View className="at-article__p">{data.wo.desc}</View>
        <AtDivider height={30} lineColor="#d6e4ef" />
        {this.renderImages()}
      </View>
    </AtAccordion>;
  }
  renderFLow(title, state_index) {
    const { data, open_state } = this.state;
    // 构造时间线
    let items = [];
    const flow = data.flow;
    // first
    for (let i = 0; i < flow.length; i++) {
      const node = flow[i];
      if (node.pre === null) {
        items.push({
          title: node.comment,
          content: [node.create_datetime + ' - ' + (node.submit_datetime ? node.submit_datetime : ''), node.from.full_name + ' 提交至 ' + node.to.full_name],
          icon: node.attitude ? node.attitude == 'passed' ? 'check' : 'close' : 'clock',
          next: node.next
        });
        break;
      }
    }
    Utils.debug('items[0].next=', items[0].next);
    // 遍历
    while (items.length > 0 && items[items.length - 1].next != null) {
      for (let i = 0; i < flow.length; i++) {
        const node = flow[i];
        if (node.id === items[items.length - 1].next.id) {
          items.push({
            title: node.comment,
            content: [node.create_datetime + ' - ' + (node.submit_datetime ? node.submit_datetime : ''), node.from.full_name + ' 提交至 ' + node.to.full_name],
            icon: node.attitude ? node.attitude == 'passed' ? 'check' : 'close' : 'clock',
            next: node.next
          });
          break;
        }
      }
    }
    Utils.debug(items);
    return <AtAccordion open={open_state[state_index]} onClick={this.handleOpenStateChanged.bind(this, state_index)} title={title}>
      <View style="padding:10px;">
        <AtTimeline pending items={items}>
        </AtTimeline>
      </View>
    </AtAccordion>;
  }
  render() {
    const { data, loading } = this.state;
    return <View>
        {this.renderCaption()}
        {loading && <AtActivityIndicator content="数据载入中..." mode="center"></AtActivityIndicator>}

        {!loading && this.renderWo('工单基本信息', 0)}
        {!loading && this.renderFLow('时间线', 5)}
        {!loading && this.renderUserInfo(data.wo.customer, '客户信息', 1)}
        {!loading && this.renderUserInfo(data.wo.dispatcher, '工单指派人', 2)}
        {!loading && this.renderUserInfo(data.wo.worker, '工单执行人', 3)}
        {!loading && this.renderResourceInfo(data.wo.res, '资源信息', 4)}

        {this.renderImagePreviewer()}
      </View>;
  }
  config = {
    navigationBarTitleText: '工单跟踪'
  };

  componentDidMount() {
    super.componentDidMount && super.componentDidMount();
  }

  componentDidShow() {
    super.componentDidShow && super.componentDidShow();
  }

  componentDidHide() {
    super.componentDidHide && super.componentDidHide();
  }

}